<template>
    <a-card
        class="general-card"
        :title="$t('chu-zhi-fen-bu')"
        :header-style="{ paddingBottom: '12px' }"
    >
        <charts
            :option="pieOptions"
            :loading="loading"
            style="height: 280px"
        ></charts>
    </a-card>
</template>

<script lang="ts" setup>
    import { ref, watch } from 'vue';
    import { useI18n } from 'vue-i18n';
    import useLoading from '@/hooks/loading';
    import Charts from '@/components/echarts/index.vue';
    import { getAnalysisData } from '../service';

    const { t } = useI18n();

    const { loading, setLoading } = useLoading();
    const renderData = ref<any[]>([]);
    function getPieOptions(data: any[]) {
        const totalAmount = data.reduce(
            (acc, item) => acc + Number(item.value),
            0
        );
        return {
            title: {
                text: t('chu-zhi-yu-e'),
                subtext: `¥ ${totalAmount}`,
                left: 'center',
                top: 'center',
            },
            grid: {
                left: 20,
            },
            legend: {
                show: true,
                bottom: 'bottom',
                orient: 'horizontal',
                icon: 'shape',
                itemWidth: 12,
                itemHeight: 12,
                textStyle: {
                    color: '#4E5969',
                },
                formatter(name: string) {
                    const target = data.find((item) => item.name === name);
                    return `${name} ${target?.value} 占比 ${target?.ratio}%`;
                },
            },
            tooltip: {
                show: true,
            },
            series: [
                {
                    name: t('chu-zhi-fen-bu'),
                    type: 'pie',
                    radius: ['55%', '75%'],
                    label: {
                        show: false,
                    },
                    data,
                },
            ],
        };
    }
    const pieOptions = ref(getPieOptions(renderData.value));

    watch(
        () => renderData.value,
        () => {
            pieOptions.value = getPieOptions(renderData.value);
        },
        { immediate: true }
    );

    async function load() {
        try {
            setLoading(true);
            const data: any = await getAnalysisData();
            renderData.value = [
                {
                    name: t('shi-ti-ka-jin-e'),
                    value: +(data.result?.cardAmount || 0),
                    ratio: data.result?.cardRatio || 0,
                },
                {
                    name: t('dian-zi-ka-jin-e'),
                    value: +(data.result?.virtualAmount || 0),
                    ratio: data.result?.virtualRatio || 0,
                },
            ];
        } finally {
            setLoading(false);
        }
    }
    load();
</script>
